package ai.plantdata.service.impl;

import ai.plantdata.config.RDBTemplateFactory;
import ai.plantdata.constant.DbTypeEnum;
import ai.plantdata.vo.rsp.Column;
import ai.plantdata.vo.rsp.TableStructureRsp;
import ai.plantdata.vo.DataSourceConfig;
import ai.plantdata.service.ReadService;
import ai.plantdata.transform.TypeTransform;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: WangHui
 * @Date: 2021/7/9 10:26
 * @Description:
 */
@Service
public class ReadServiceImpl implements ReadService {
    @Override
    public List<TableStructureRsp> getStructure(DataSourceConfig dataSourceMsg) {
        try {
            DbTypeEnum from = DbTypeEnum.from(dataSourceMsg.getType());
            DataSource source = RDBTemplateFactory.factory(dataSourceMsg, from);
            Connection conn = source.getConnection();
            DatabaseMetaData dataSource = conn.getMetaData();
            ResultSet tables = dataSource.getTables(null, null, "%", new String[]{"TABLE"});
            List<String> tableNames = new ArrayList<>();
            while (tables.next()) {
                String tableName = tables.getString("TABLE_NAME");
                tableNames.add(tableName);
            }
            if (CollectionUtils.isEmpty(tableNames)) {
                return null;
            }
            List<TableStructureRsp> tableStructureReqs = new ArrayList<>();
            for (String tableName : tableNames) {
                TableStructureRsp tableStructureReq = new TableStructureRsp();
                tableStructureReq.setName(tableName);
                ResultSet rs = dataSource.getColumns(null, null, tableName, "%");
                List<Column> columns = new ArrayList<>();
                while (rs.next()) {
                    Column column = new Column();
                    String columnName = rs.getString("COLUMN_NAME");
                    column.setName(columnName);
                    String remarks = rs.getString("REMARKS");
                    column.setDescription(remarks);
                    Class<?> dataType = TypeTransform.jdbcTypeToJavaType(rs.getInt("DATA_TYPE"));
                    column.setJdbcCode(rs.getInt("DATA_TYPE"));
                    column.setClassType(dataType);
                    columns.add(column);
                }
                rs.close();
                tableStructureReq.setColumns(columns);
                tableStructureReqs.add(tableStructureReq);
            }

            conn.close();
            return tableStructureReqs;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
